package service

import (
	"log"

	"gitee.com/gldmmhh/bbs/data_service"
	"gitee.com/gldmmhh/kiteclient/kitex_gen/bbs"
)

// GetUserPostsLogic 获取用户帖子列表业务逻辑
func GetUserPostsLogic(userID int64, page, size int) (*bbs.GetUserPostsResponse, error) {
	posts, total, err := data_service.GetUserPosts(userID, page, size)
	if err != nil {
		log.Printf("GetUserPostsLogicFail err: %v userID: %d", err, userID)
		return &bbs.GetUserPostsResponse{
			Code:    500,
			Message: "获取用户帖子失败",
		}, err
	}

	postSummaries := make([]*bbs.PostSummary, 0, len(posts))
	for _, p := range posts {
		postSummaries = append(postSummaries, &bbs.PostSummary{
			Id:      p.Id,
			Summary: p.Summary,
			LikeNum: int32(p.LikeNum),
		})
	}

	pages := (total + int64(size) - 1) / int64(size)
	return &bbs.GetUserPostsResponse{
		Code:    200,
		Message: "success",
		Data: &bbs.UserPostsData{
			Total:       int32(total),
			Pages:       int32(pages),
			CurrentPage: int32(page),
			Posts:       postSummaries,
		},
	}, nil
}

// GetPostsLogic 获取帖子列表业务逻辑
func GetPostsLogic(page, limit int, sort, order string) (*bbs.GetPostsResponse, error) {
	log.Printf("GetPostsLogic page: %d, limit: %d, sort: %s, order: %s", page, limit, sort, order)
	posts, total, err := data_service.GetPosts(page, limit, sort, order)
	if err != nil {
		log.Printf("GetPostsLogicFail err: %v", err)
		return &bbs.GetPostsResponse{}, err
	}
	log.Printf("GetPostsLogicSuccess total: %v", total)

	postBriefs := make([]*bbs.PostBrief, 0, len(posts))
	for _, p := range posts {
		postBriefs = append(postBriefs, &bbs.PostBrief{
			Id:         p.Id,
			Summary:    p.Summary,
			Writer:     "", // TODO: 需要根据Writer ID获取用户名
			UpdateTime: p.UpdateTime.Format("2006-01-02 15:04:05"),
		})
	}

	pages := (total + int64(limit) - 1) / int64(limit)
	return &bbs.GetPostsResponse{
		Posts: postBriefs,
		Total: int32(total),
		Page:  int32(page),
		Pages: int32(pages),
	}, nil
}

// GetPostDetailLogic 获取帖子详情业务逻辑
func GetPostDetailLogic(postID, userID int64) (*bbs.GetPostDetailResponse, error) {
	// 使用data_service的GetPostDetail方法
	post, isLiked, isSaved, err := data_service.GetPostDetail(postID, userID)
	if err != nil {
		return &bbs.GetPostDetailResponse{
			Code:    500,
			Message: "获取帖子详情失败",
		}, nil
	}

	if post == nil {
		return &bbs.GetPostDetailResponse{
			Code:    404,
			Message: "帖子不存在",
		}, nil
	}

	// 获取作者信息
	author, _ := data_service.GetUserInfo(post.Writer)
	authorName := ""
	if author != nil {
		authorName = author.Name
	}

	return &bbs.GetPostDetailResponse{
		Code:    200,
		Message: "success",
		Data: &bbs.PostDetail{
			Id:      post.Id,
			Summary: post.Summary,
			Writer: &bbs.Writer{
				Id:   post.Writer,
				Name: authorName,
			},
			UpdateTime: post.UpdateTime.Format("2006-01-02 15:04:05"),
			Content:    post.Content,
			LikeNum:    int32(post.LikeNum),
			SaveNum:    int32(post.SaveNum),
			CommentNum: int32(post.CommentNum),
			IsLiked:    isLiked,
			IsSaved:    isSaved,
		},
	}, nil
}

// LikePostLogic 点赞帖子业务逻辑
func LikePostLogic(postID, likerID int64) (*bbs.LikePostResponse, error) {
	err := data_service.LikePost(postID, likerID)
	if err != nil {
		return &bbs.LikePostResponse{
			Code:    500,
			Message: "点赞失败: " + err.Error(),
		}, nil
	}

	return &bbs.LikePostResponse{
		Code:    200,
		Message: "点赞成功",
	}, nil
}

// CancelLikePostLogic 取消点赞业务逻辑
func CancelLikePostLogic(postID, likerID int64) (*bbs.CancelLikePostResponse, error) {
	err := data_service.UnlikePost(postID, likerID)
	if err != nil {
		return &bbs.CancelLikePostResponse{
			Code:    500,
			Message: "取消点赞失败: " + err.Error(),
		}, nil
	}

	return &bbs.CancelLikePostResponse{
		Code:    200,
		Message: "取消点赞成功",
	}, nil
}

// SavePostLogic 收藏帖子业务逻辑
func SavePostLogic(postID, saverID int64) (*bbs.SavePostResponse, error) {
	err := data_service.SavePost(postID, saverID)
	if err != nil {
		return &bbs.SavePostResponse{
			Code:    500,
			Message: "收藏失败: " + err.Error(),
		}, nil
	}

	return &bbs.SavePostResponse{
		Code:    200,
		Message: "收藏成功",
	}, nil
}

// CancelSavePostLogic 取消收藏业务逻辑
func CancelSavePostLogic(postID, saverID int64) (*bbs.CancelSavePostResponse, error) {
	err := data_service.UnsavePost(postID, saverID)
	if err != nil {
		return &bbs.CancelSavePostResponse{
			Code:    500,
			Message: "取消收藏失败: " + err.Error(),
		}, nil
	}

	return &bbs.CancelSavePostResponse{
		Code:    200,
		Message: "取消收藏成功",
	}, nil
}

// CreatePostLogic 创建帖子业务逻辑
func CreatePostLogic(writer int64, summary, content string) (*bbs.CreatePostResponse, error) {

	postID, err := data_service.CreatePost(writer, summary, content)
	if err != nil {
		return &bbs.CreatePostResponse{
			Code:    500,
			Message: "创建帖子失败: " + err.Error(),
		}, nil
	}

	return &bbs.CreatePostResponse{
		Code:    200,
		Message: "创建帖子成功",
		PostId:  postID,
	}, nil
}

// UpdatePostLogic 更新帖子业务逻辑
func UpdatePostLogic(postID int64, summary, content string) (*bbs.UpdatePostResponse, error) {
	err := data_service.UpdatePost(postID, summary, content)
	if err != nil {
		return &bbs.UpdatePostResponse{
			Code:    500,
			Message: "更新帖子失败: " + err.Error(),
		}, nil
	}

	return &bbs.UpdatePostResponse{
		Code:    200,
		Message: "更新帖子成功",
	}, nil
}

// DeletePostLogic 删除帖子业务逻辑
func DeletePostLogic(postID, userID int64) (*bbs.DeletePostResponse, error) {
	err := data_service.DeletePost(postID, userID)
	if err != nil {
		return &bbs.DeletePostResponse{
			Code:    500,
			Message: "删除帖子失败: " + err.Error(),
		}, nil
	}

	return &bbs.DeletePostResponse{
		Code:    200,
		Message: "删除帖子成功",
	}, nil
}

// generateDefaultTitle 生成默认标题
func generateDefaultTitle(content string) string {
	// 从内容中提取前20个字符作为默认标题
	if len(content) == 0 {
		return "无标题帖子"
	}

	if len(content) > 20 {
		return content[:20] + "..."
	}
	return content
}
